<template>
    <view>
        <view style="margin: 20rpx; color: #ccc;">
            ① 请添加持卡人本人的银行卡<br />
            ② 请谨慎确认填入银行卡<br />
            ③ 如果添错后面提现成功不可回退
        </view>
        <view style="background-color: white">
            <up-cell :title="way.title" isLink clickable arrowDirection='down' @click="openSelect"></up-cell>
            <up-form :model="form" :rules="way.value === 1 ? rules : rules2" label-width="90px" ref="formRef">
                <view class="form_part">
                    <up-form-item label="名字" border-bottom>
                        <up-input border="none" disabled v-model="name" disabledColor='#fff' />
                    </up-form-item>
                    <up-form-item label="银行卡号" prop="bankAccount" border-bottom>
                        <up-input placeholder="请输入完整银行卡号" border="none" v-model="form.bankAccount" />
                    </up-form-item>
                    <up-form-item label="开户行" prop="bank" border-bottom>
                        <div @click="openSelectBank">
                            <up-input placeholder="请输入开户行" border="none" v-model="form.bank" disabled
                                disabledColor="#fff" />
                        </div>
                    </up-form-item>
                    <up-form-item label="手机号" prop="phoneNumber" border-bottom>
                        <up-input type="number" placeholder="请输入银行卡预留手机号" border="none" v-model="form.phoneNumber" />
                    </up-form-item>
                    <up-form-item v-if='way.value === 2' label="金额" prop="amount" border-bottom>
                        <up-input placeholder="请输入金额" border="none" v-model="form.amount" />
                    </up-form-item>
                    <up-form-item label="验证码" prop="code">
                        <up-input border="none" v-model="form.code" placeholder="请输入验证码"></up-input>
                        <template v-slot:right>
                            <div style="width: 80px;">
                                <up-code ref="uCode" @change="codeChange"></up-code>
                                <up-button style="height: 35px;" type="primary" @tap="getCode"><span
                                        style="font-size: 10px;">{{ tips }}</span></up-button>
                            </div>
                        </template>
                    </up-form-item>
                </view>
            </up-form>
        </view>
        <view class="form_button">
            <up-button type="primary" @click="bindCard">添加</up-button>
        </view>
    </view>


    <up-popup :show="showPopup" mode="center" :round="5" zoom @close="close" :safeAreaInsetBottom="false">
        <view style="width: 650rpx;height: 80vh;display: flex;flex-direction: column;">
            <div style="text-align: center;padding: 5px;">请选择银行</div>
            <view style="padding: 5px;display: flex;justify-content: space-between;align-items: center;">
                <up-input style="flex: 1;" placeholder="请输入银行名称" v-model="getBankParams.bankname" :clearable="true">
                    <template #prefix>
                        <up-icon name="search"></up-icon>
                    </template>
                </up-input>
                <up-button style="width: 50px;height: 38px;" type="primary" text="搜索" @click="search"></up-button>
            </view>
            <div style="height: calc(80vh - 50px);overflow: auto;">
                <up-list :lowerThreshold='100'>
                    <up-list-item
                        :style="{ 'background-color': item.agentbankcode === bankItem.agentbankcode ? '#d3e3fd' : '' }"
                        v-for="item in bankList" :key="item.agentbankcode">
                        <up-cell :title="item.bankname" @click="clickItem(item)"></up-cell>
                    </up-list-item>
                </up-list>
            </div>
            <div style="display: flex;justify-content: space-around;align-items: center;">
                <up-button style="width: 50%;" text="取消" @click="close()"></up-button>
                <up-button style="width: 50%;" type="primary" text="确认" @click="confirmBank"></up-button>
            </div>
        </view>
    </up-popup>

    <up-picker :show="showPicker" :columns="columns" keyName="title" @confirm="confirmSelect"
        @cancel="cancelSelect"></up-picker>

    <up-toast ref="uToastRef"></up-toast>

</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { getUserProfile } from '@/api/user'
import {
    bindSmsCode,
    addBankCard,
    getBankList,
    getSmallAmountCode,
    checkAmountWithCorp
} from '@/api/driver'
import {
    showConfirm
} from '@/utils/common'


/* 数据 */
const uToastRef = ref<any>(null)
const formRef = ref<UniFormRef | null>(null)
const showPopup = ref(false)
const showPicker = ref(false)
const name = ref('')
// 表单
const form = reactive({
    bankAccount: '',
    bank: '',
    phoneNumber: '',
    code: '',
    amount: ''
})
// 普通绑卡校验规则
const rules = reactive({
    bankAccount: [{
        type: 'string',
        required: true,
        message: '请填写银行卡号',
        trigger: ['blur', 'change']
    },
    {
        pattern: /^\d{16,19}$/,
        message: '请输入有效的银行卡号',
        trigger: ['blur', 'change']
    },
    ],
    phoneNumber: [{
        required: true,
        message: '手机号不能为空',
        trigger: ['blur', 'change']
    },
    {
        pattern: /(^1[3-9][0-9]{9}$)/g,
        message: '手机格式错误',
        trigger: ['blur', 'change']
    },
    ],
    bank: {
        type: 'string',
        required: true,
        message: '请填写开户行',
        trigger: ['blur', 'change']
    },
    code: {
        type: 'string',
        required: true,
        message: '请填写验证码',
        trigger: ['blur', 'change']
    }
})
// 小额绑卡校验规则
const rules2 = reactive({
    bankAccount: [{
        type: 'string',
        required: true,
        message: '请填写银行卡号',
        trigger: ['blur', 'change']
    },
    {
        pattern: /^\d{16,19}$/,
        message: '请输入有效的银行卡号',
        trigger: ['blur', 'change']
    }],
    phoneNumber: [{
        required: true,
        message: '手机号不能为空',
        trigger: ['blur', 'change']
    },
    {
        pattern: /(^1[3-9][0-9]{9}$)/g,
        message: '手机格式错误',
        trigger: ['blur', 'change']
    }],
    bank: {
        type: 'string',
        required: true,
        message: '请填写开户行',
        trigger: ['blur', 'change']
    },
    code: {
        type: 'string',
        required: true,
        message: '请填写验证码',
        trigger: ['blur', 'change']
    },
    amount: {
        type: 'number',
        required: true,
        message: '请填写金额',
        trigger: ['blur', 'change']
    }
})
// 绑卡模式
const way = reactive({
    title: '普通绑卡',
    value: 1
})
const columns = ref([
    [{
        title: '普通绑卡',
        value: 1
    },
    {
        title: '小额绑卡',
        value: 2
    }]
])
// 获取银行列表
const getBankParams = reactive({
    bankname: "", //开户行名称
    currPage: 1, //当前页
    limit: 50 //当前数据条数
})
//银行列表
const bankList = reactive<any[]>([])
// 点击选中的银行
const bankItem = reactive<any>({})
// 验证码提示
const tips = ref('')
// 获取验证码按钮
const uCode = ref<any>(null)



/* 方法 */
// 绑卡
const bindCard = async () => {
    let valid = await formRef.value?.validate()
    if (valid) {
        const resModal = await showConfirm(`请确认提现银行卡号是否正确：\n${form.bankAccount}`)
        if (!resModal.confirm) return
        uToastRef.value.show({
            type: 'loading',
            message: "正在绑定银行卡",
            duration: -1
        })
    }
    let fn = null
    let params = null
    if (way.value === 1) {
        fn = addBankCard
        params = { ...form }
    } else {
        fn = checkAmountWithCorp
        params = {
            ...form,
            phone: form.phoneNumber
        }
    }
    const res = await fn(params)
    if (res.success) {
        uToastRef.value.show({
            message: '绑定成功',
            type: 'success',
            position: 'top',
            complete() {
                uni.navigateBack()
            }
        })
    }
}
const codeChange = (text: string) => {
    tips.value = text
}
// 获取验证码
const getCode = async () => {
    if (!form.phoneNumber) {
        uToastRef.value.show({
            position: "top",
            type: 'warning',
            message: "请先填写手机号"
        })
        return
    }
    if (!form.bankAccount) {
        uToastRef.value.show({
            position: "top",
            type: 'warning',
            message: "请先填写银行卡号"
        })
        return
    }
    if (!form.bank) {
        uToastRef.value.show({
            position: "top",
            type: 'warning',
            message: "请先选择开户行"
        })
        return
    }
    if (uCode.value.canGetCode) {
        uToastRef.value.show({
            type: 'loading',
            message: "正在获取验证码",
            duration: -1
        })
        let params = {
            bankAccount: form.bankAccount,
            bank: form.bank,
            phone: form.phoneNumber
        }
        let fn = null
        if (way.value === 1) {
            fn = bindSmsCode
        } else {
            fn = getSmallAmountCode
        }
        let codeRes = await fn(params)
        uToastRef.value.hide()
        if (codeRes.success) {
            uToastRef.value.show({
                position: "top",
                type: 'success',
                message: "验证码已发送"
            })
        }
        // 通知验证码组件内部开始倒计时
        uCode.value.start()
    } else {
        uToastRef.value.show({
            position: "top",
            type: 'warning',
            message: "倒计时结束后再发送"
        })
    }
}
// 打开选择模式
const openSelect = () => {
    showPicker.value = true
}
// 选择模式
const confirmSelect = (e: any) => {
    Object.assign(way, e.value[0])
    cancelSelect()
}
// 关闭选择模式
const cancelSelect = () => {
    showPicker.value = false
}
// 获取银行列表
const getBanks = async () => {
    uToastRef.value.show({
        message: "加载中",
        type: 'loading',
        duration: -1
    })
    let res = await getBankList(getBankParams)
    uToastRef.value.hide()
    if (res.success) {
        bankList.push(...res.data.list)
    }
}
// 搜索银行
const search = async () => {
    bankList.length = 0
    getBankParams.currPage = 1
    await getBanks()
}
// 点击银行
const clickItem = (item: any) => {
    Object.assign(bankItem, item)
}
// 确认选择银行
const confirmBank = () => {
    form.bank = bankItem.bankname
    close()
}
// 打开选择银行popup
const openSelectBank = () => {
    showPopup.value = true
}
// 关闭选择银行popup
const close = () => {
    showPopup.value = false
}
// 获取用户姓名
const getUserInfo = async () => {
    uToastRef.value.show({
        message: "正在获取用户信息",
        type: 'loading',
        duration: -1
    })
    let res = await getUserProfile()
    uToastRef.value.hide()
    if (res.success) {
        name.value = res.data.name
    }
}
// 初始化封装
const init = async () => {
    await getUserInfo()
    await getBanks()
}



/* 钩子 */
onMounted(async () => {
    await init()
})


</script>

<style scoped>
button {
    width: 90%;
}

.form_part {
    background-color: #fff;
    padding: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
}

.form_button {
    margin-left: 5%;
    width: 90%;
}
</style>
